package com.hongdee.crm.task.service.impl;

import com.hongdee.annotation.MethodComment;
import com.hongdee.common.util.DateUtils;
import com.hongdee.crm.car.entity.TCrmCar;
import com.hongdee.crm.carConfig.service.ITCrmCarWarrantyService;
import com.hongdee.crm.exsurance.entity.TCrmCarExsurance;
import com.hongdee.crm.maintain.entity.TCrmCarMaintain;
import com.hongdee.crm.task.dao.ITCrmCarMaintainTaskDao;
import com.hongdee.crm.task.dao.ITCrmCarWarrantyTaskDao;
import com.hongdee.crm.task.dto.CarBrandDTO;
import com.hongdee.crm.task.dto.CarGuaranteedDTO;
import com.hongdee.crm.task.dto.CarSeriesDTO;
import com.hongdee.crm.task.service.ITCrmCarWarrantyTaskService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 名  称: TCrmCarExsuranceTaskServiceImpl
 * 类  型: class
 * 描  述: 车辆延保更新其状态信息
 * 路  径: com.hongdee.crm.task.service.impl
 * 作  者: wangshuai
 * 日  期:2017/2/28 10:23
 */
@Service
public class TCrmCarWarrantyTaskServiceImpl implements ITCrmCarWarrantyTaskService {

    private Logger logger = LoggerFactory.getLogger(TCrmCarWarrantyTaskServiceImpl.class);

    @Autowired
    private ITCrmCarWarrantyTaskDao crmCarExsuranceTaskDao;
    @Autowired
    private ITCrmCarMaintainTaskDao crmCarMaintainTaskDao;

    @Autowired
    private ITCrmCarWarrantyService crmCarWarrantyService;

    private final Long DEFTIME=1377964800000L;

    private enum MILSTATUS{
        NOTSTART,START,STOP
    }

    private final int LIMIT=1000;

    @Override
    @MethodComment(name = "更新车辆延保状态")
    public Integer updCarExsuranceInfoQuartz() throws Exception {
        logger.info("开始执行车辆续保平均里程、延保状态定时任务"+System.currentTimeMillis());
        Integer nums=0;
        int start=0;
        while(true){
            logger.info("遍历第"+start+"次"+System.currentTimeMillis());
            String sql="select * from t_crm_car_exsurance where CONVERT(mile_status,SIGNED) <2 AND mile_status is NOT NULL " +
                    "AND restart_insurance is not NULL AND start_legend is not null AND stop_legend is not null limit ?,?";
            List<Map<String,Object>> mapList=crmCarExsuranceTaskDao.findCarExsuranceLists(sql,start*LIMIT,LIMIT);
            if(mapList==null){
                start=0;
                break;
            }
            List<TCrmCarExsurance> lists=this.analyCarExsuranceList(mapList);
            if(lists.size()>0){
                nums+=lists.size();
                crmCarExsuranceTaskDao.updBatchCarExsucrance(lists);
            }
            logger.info("结束"+System.currentTimeMillis());
            start++;
        }
        while(true){
            logger.info("遍历第"+start+"次"+System.currentTimeMillis());
            String sql="select * from t_crm_car_exsurance where mile_status is NULL AND restart_insurance is not NULL " +
                    "AND start_legend is not null AND stop_legend is not null limit ?,?";
            List<Map<String,Object>> mapList=crmCarExsuranceTaskDao.findCarExsuranceLists(sql,start,LIMIT);
            if(mapList==null){
                start=0;
                break;
            }
            List<TCrmCarExsurance> lists=this.analyCarExsuranceList(mapList);
            if(lists.size()>0){
                nums+=lists.size();
                crmCarExsuranceTaskDao.updBatchCarExsucrance(lists);
            }
            logger.info("结束"+System.currentTimeMillis());
        }
        return nums;
    }



    /**
     * 解析查询到的车辆续保信息
     * @param mapList 车辆续保信息
     * @return
     * @throws Exception
     */
    private List<TCrmCarExsurance> analyCarExsuranceList(List<Map<String,Object>> mapList) throws Exception {
        List<TCrmCarExsurance> list=new ArrayList<>();
        for (Map<String,Object> map:mapList) {
            //取出车辆ID
            String carId=String.valueOf(map.get("user_carid"));
            //车架号
            String vin=String.valueOf(map.get("vin"));
            //查询出车辆所有的保养工单信息
            List<TCrmCarMaintain> crmCarMaintains=crmCarMaintainTaskDao.findMaintainByCarId(carId,vin);
            if(crmCarMaintains.size()==0){
                String id = String.valueOf(map.get("id"));
                TCrmCarExsurance crmCarExsurance = new TCrmCarExsurance();
                crmCarExsurance.setMileStatus(String.valueOf(MILSTATUS.NOTSTART.ordinal()));
                crmCarExsurance.setId(id);
                list.add(crmCarExsurance);
            }else {
                String id = String.valueOf(map.get("id"));
                TCrmCarExsurance crmCarExsurance = new TCrmCarExsurance();
                //车辆延保开始和结束时间
                Long startTime = Long.valueOf(String.valueOf(map.get("restart_insurance")));
                Long stopTime =null;
                if(map.get("restop_insurance")==null){
                    //默认设置年份为一年
                    int retime=1;
                    if(map.get("retime")!=null){
                        String retimeStr=String.valueOf(map.get("retime"));
                        retimeStr=retimeStr.replaceAll("年","");
                        retime=Integer.valueOf(retimeStr);
                    }
                    startTime=DateUtils.addMonthLongTime(startTime,retime*12);
                }else{
                    stopTime=Long.valueOf(String.valueOf(map.get("restop_insurance")));
                }
                //车辆保养里程起始
                Float startMile = Float.valueOf(String.valueOf(map.get("start_legend")));
                Float stopMile = Float.valueOf(String.valueOf(map.get("stop_legend")));
                //最后一次保养内容
                TCrmCarMaintain crmCarMaintain = crmCarMaintains.get(crmCarMaintains.size() - 1);
                //最后一次的保里程
                Float maintainMile = Float.valueOf(String.valueOf(crmCarMaintain.getMaintainMile()));
                //最后一次保养时间
                Long maintainTime = Long.valueOf(String.valueOf(crmCarMaintain.getMaintainTime()));
                //平均保养里程
                Float avgMile = maintainMile / crmCarMaintains.size();
                crmCarExsurance.setAvgMile(avgMile.toString());
                //根据保养里程、最后一次保养时间与续保的合同起止时间、里程起止数判断在保状态
                if (maintainTime < startTime || maintainMile < startMile) {
                    crmCarExsurance.setMileStatus(String.valueOf(MILSTATUS.NOTSTART.ordinal()));
                }
                if ((maintainTime >= startTime && maintainTime <= stopTime) || (maintainMile >= startMile && maintainMile <= stopMile)) {
                    crmCarExsurance.setMileStatus(String.valueOf(MILSTATUS.START.ordinal()));
                }
                if (maintainTime > stopTime || maintainMile > stopMile) {
                    crmCarExsurance.setMileStatus(String.valueOf(MILSTATUS.STOP.ordinal()));
                }
//                crmCarExsurance.setUserCarId(carId);
//                crmCarExsurance.setVin(vin);
                crmCarExsurance.setId(id);
                list.add(crmCarExsurance);
            }

        }
        return list;
    }



    /**
     * 更新车辆质保状态
     * @throws Exception
     */
    @Override
    @MethodComment(name = "更新车辆质保状态")
    public Integer updCarWarrantyInfoQuartz() throws Exception {
        logger.info("开始执行车辆质保状态定时任务"+System.currentTimeMillis());
        Integer nums=0;
        //获得质保参数信息
        List<CarBrandDTO> carBrandList=crmCarWarrantyService.findZbParamList("car_zb");
        int start=0;
        while(true){
            logger.info("开始执行车辆质保状态定时任务：第"+start+"   开始时间："+System.currentTimeMillis());
            List<TCrmCar> crmCars=crmCarExsuranceTaskDao.findCarByMileStatus(start*LIMIT,LIMIT);
            if(crmCars==null){
                start=0;
                break;
            }
            List<TCrmCar> list=this.analyCarWarrantyList(crmCars,carBrandList);
            if(list.size()>0){
                nums+=list.size();
                crmCarExsuranceTaskDao.updBatchCarWarranty(list);
            }
            logger.info("开始执行车辆质保状态定时任务：第"+start+"   结束时间："+System.currentTimeMillis());
            start++;
        }
        while(true){
            logger.info("开始执行车辆质保状态定时任务：第"+start+"   开始时间："+System.currentTimeMillis());
            List<TCrmCar> crmCars=crmCarExsuranceTaskDao.findCarByMileStatusIsNull(start*LIMIT,LIMIT);
            if(crmCars==null){
                start=0;
                break;
            }
            List<TCrmCar> list=this.analyCarWarrantyList(crmCars,carBrandList);
            if(list.size()>0){
                nums+=list.size();
                crmCarExsuranceTaskDao.updBatchCarWarranty(list);
            }
            logger.info("开始执行车辆质保状态定时任务：第"+start+"   结束时间："+System.currentTimeMillis());
        }
        return nums;
    }

    /**
     * 遍历车辆信息
     * @param crmCars
     * @param carBrandList
     * @return
     * @throws Exception
     */
    private List<TCrmCar> analyCarWarrantyList(List<TCrmCar> crmCars,List<CarBrandDTO> carBrandList) throws Exception {
//        logger.info("开始执行车辆质保状态定时任务:遍历车辆信息");
        List<TCrmCar> list=new ArrayList<>();
        for (int i=0;i<crmCars.size();i++) {
            TCrmCar car=crmCars.get(i);
            //遍历质保信息，将车辆信息与质保信息进行对比
            Integer mileStatus=this.analyCarBrand(car,carBrandList);
            if(mileStatus==null){
                mileStatus=0;
            }
            car.setMileStatus(mileStatus.toString());
            list.add(car);
        }

        return list;
    }

    /**
     * 遍历质保信息中的品牌信息，先将车辆品牌与质保集合中的品牌进行对比
     * @param car
     * @param carBrandList
     * @return
     * @throws Exception
     */
    private Integer analyCarBrand(TCrmCar car,List<CarBrandDTO> carBrandList) throws Exception {
//        logger.info("开始执行车辆质保状态定时任务:遍历质保信息中的品牌信息");
        //品牌信息
        String brand=String.valueOf(car.getBrand());
        for (CarBrandDTO brandDto:carBrandList) {
            //品牌相同
            if(brand.equals(brandDto.getCode())){
                return this.analyCarSerieList(brandDto,car);
            }
        }
        return null;
    }

    /**
     * 遍历车系信息，将车辆信息与车系进行对比
     * @param brandDto
     * @param car
     * @return
     * @throws Exception
     */
    private Integer analyCarSerieList(CarBrandDTO brandDto,TCrmCar car) throws Exception {
//        logger.info("开始执行车辆质保状态定时任务:遍历车系");
        //遍历车系
        if(brandDto.getCarSeriesDTOS()!=null){
            if(brandDto.getCarSeriesDTOS().size()>0){
                //车系信息
                String series=String.valueOf(car.getSeries());
                for (CarSeriesDTO seriesDto:brandDto.getCarSeriesDTOS()) {
                    //判断车系统名称是否与品牌名称相同
                    if((brandDto.getCode()).equals(seriesDto.getCode())){
                        return this.analyCaarGuaranteed(seriesDto.getCarGuaranteedDTOS(),car);
                    }
                    //判断车辆车系信息 与车系名称相同
                    if(series.equals(seriesDto.getCode())){
                        return this.analyCaarGuaranteed(seriesDto.getCarGuaranteedDTOS(),car);
                    }
                }
            }
        }
        return null;
    }

    /**
     * 根据质保信息中的，对比车辆信息
     * @param carGuaranteedDTOList
     * @param car
     * @return
     * @throws Exception
     */
    private Integer analyCaarGuaranteed(List<CarGuaranteedDTO> carGuaranteedDTOList, TCrmCar car) throws Exception {
//        logger.info("开始执行车辆质保状态定时任务:根据质保信息中的，对比车辆信息");
        //质保开始时间
        Long guaranteeDate=null;
        if(car.getGuaranteeStartDate()!=null){
            guaranteeDate=Long.valueOf(car.getGuaranteeStartDate());
        }
        //行驶里程信息
        Float runMile=null;
        if(car.getRunMile()!=null){
            runMile=Float.valueOf(car.getRunMile());
        }
        //质保时间为空
        if(car.getGuaranteeStartDate()==null || "".equals(car.getGuaranteeStartDate())){
            return MILSTATUS.NOTSTART.ordinal();
        }

        //遍历质保信息
        for (CarGuaranteedDTO guaranteedDto:carGuaranteedDTOList) {
            String code=guaranteedDto.getCode();
            String lastStr=code.substring(code.lastIndexOf("_")+1,code.length());
            Long timePoint=DateUtils.dayToLongTime(guaranteedDto.getTimePoint());
            boolean warrantyFlag=false;
            //0日期之前
            if(lastStr.equals("0")){
                //判断质保时间小于时间点
                if(guaranteeDate<timePoint) {
                    warrantyFlag=true;
                }
            }
            if(lastStr.equals("1")){
                //1日期之后
                //判断质保时间大于时间点
                if(guaranteeDate>=timePoint) {
                    warrantyFlag=true;
                }
            }
            if(warrantyFlag){
                //质保定义
                Float month=Float.valueOf(guaranteedDto.getYear())*12;
                Float mile=Float.valueOf(guaranteedDto.getMile());
                return this.checkCarWarranty(guaranteeDate, runMile, month, mile);
            }
        }
        return null;
    }

    private Integer checkCarWarranty(Long guaranteeDate,Float runMile,Float month,Float mile) throws Exception {
        //判断质保开始时间 与现在相差多少天
        Long nowTime=new Date().getTime();
        //由质保算起 算出结束时间
        Long guaranteeEnd= DateUtils.addMonthLongTime(guaranteeDate,month.intValue());
        //当前里程
        if(nowTime<guaranteeDate){
            return MILSTATUS.NOTSTART.ordinal();
        }
        if(nowTime>=guaranteeDate && nowTime<=guaranteeEnd ){
            return MILSTATUS.START.ordinal();
        }
        if(nowTime>guaranteeEnd){
            return MILSTATUS.STOP.ordinal();
        }
        if(runMile!=null){
            if(runMile<0){
                return MILSTATUS.NOTSTART.ordinal();
            }
            if(runMile>=0 && runMile<=mile){
                return MILSTATUS.START.ordinal();
            }
            if(runMile>mile){
                return MILSTATUS.STOP.ordinal();
            }
        }
        return MILSTATUS.NOTSTART.ordinal();
    }

}
